
package bibliotheque.server;

import bibliotheque.wave.WaveAction;
import bibliotheque.wave.WaveAgent;

public class StopAction extends WaveAction {
    
    public StopAction() {
        
    }
    
    public void PropagateAfter(WaveAgent agent) throws Exception {
        final Server server;
        Thread thread;
        if(agent instanceof Server) {
            server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                if(server.state == Server.State.STOP) throw new Exception("Stop failed cause server state is stopped.");
                
                server.state = Server.State.STOPPING;
                server.StateChanged(server.state.toString());
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
                throw ex;
            } finally {
                server.mutex.release();
            }
        }
    }
    
    public void LocalEnd(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                if(server.state == Server.State.STOP) throw new Exception("Selection failed cause server state is stopped.");
               
                if(server.state == Server.State.STOPPING && server.transaction_manager.GetNbUseDocument() == 0 && server.GetNbWaves() == 0) {
                    server.state = Server.State.STOP;
                    server.StateChanged(server.state.toString());
                }
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
                throw ex;
            } finally {
                server.mutex.release();
            }
        }
    }
    
    public void GlobalEnd(WaveAgent agent) throws Exception {
        Server server;
        if(agent instanceof Server) {
            server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                server.name_server.Stopped();
            } catch (Exception ex) {
                server.ErrorOccured("Stop failed cause the name_server returns an error.");
            } finally {
                server.mutex.release();
            }
        }
    }
}
